package com.xjiye_test.payServer.servletGroup.shemmapay;

import com.xiaoleilu.hutool.json.JSONObject;
import com.xiaoleilu.hutool.json.JSONUtil;
import com.xiaoleilu.hutool.util.BeanUtil;
import com.xiaoleilu.hutool.util.NumberUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import com.xjiye_test.payServer.dao.SmfOrderDao;
import com.xjiye_test.payServer.pojo.SmfPayInfo;
import com.xjiye_test.payServer.serverletUtil.HttpUtil;
import com.xjiye_test.payServer.serverletUtil.IdWorker;
import com.xjiye_test.payServer.serverletUtil.PaySignature;
import com.xjiye_test.payServer.serverletUtil.PlatformPayException;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URISyntaxException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class PaySmf extends HttpServlet {

    public String toPay(SmfPayInfo pay){
        Map<String,Object> orderPayMap=new TreeMap<>();
        orderPayMap.putAll(BeanUtil.beanToMap(pay));
        String biz_content="";
        for(Map.Entry var:orderPayMap.entrySet()){
            if(null!=var.getValue().toString()&&var.getValue().toString().length()>0){
                biz_content+=var.getKey()+"="+var.getValue()+"&";
            }
        }
        biz_content= StrUtil.sub(biz_content,0,-1);
        try {
            biz_content=PaySignature.rsaEncrypt(biz_content,GlobalVariable.publicKey,GlobalVariable.charset);
        } catch (PlatformPayException e) {
            e.printStackTrace();
            return "fail";
        }
        String sign= null;
        try {
            sign = PaySignature.rsaSign(biz_content, GlobalVariable.privateKey,GlobalVariable.charset,GlobalVariable.signType);
        } catch (PlatformPayException e) {
            e.printStackTrace();
            return "fail";
        }
        Map<String,String> reqVar=new HashMap<>();
        reqVar.put("biz_content",biz_content);
        reqVar.put("sign",sign);
        reqVar.put("sign_type",GlobalVariable.signType);
        reqVar.put("charset",GlobalVariable.charset);
        reqVar.put("s_id",GlobalVariable.sID);
        Map<String,String> header=new HashMap<>();
        header.put("Content-Type","application/json");
        try {
            HttpResponse result =HttpUtil.getInstance().doPost(GlobalVariable.payUrl+"/p", JSONUtil.toJsonStr(reqVar),header);
            if (result.getStatusLine().getStatusCode() == 200) {
                JSONObject json=JSONUtil.parseObj(EntityUtils.toString(result.getEntity()));
                if("100".equals(json.getStr("msgcode"))){
                    SmfOrderDao smfdao=new SmfOrderDao();
                    smfdao.addSmfPayInfo(pay,GlobalVariable.sID,json.getJSONObject("msg").getStr("payNo"));
                }
                return json.toString();
            }else {
                return EntityUtils.toString(result.getEntity());
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return "fail";
        } catch (IOException e) {
            e.printStackTrace();
            return "fail";
        } catch (SQLException e) {
            e.printStackTrace();
            return "fail";
        }
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("content-type","text/html;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        String amount=req.getParameter("amount");
        String pay_type=req.getParameter("type");
        String pay_channel=req.getParameter("channel");
        String auth_code=req.getParameter("code");
        String notify_url=req.getParameter("notifyurl");
        SmfPayInfo smf=new SmfPayInfo();
        if(null!=amount&&amount.length()>0){
            smf.setAmount(Integer.parseInt(amount));
        }else{
            smf.setAmount(NumberUtil.generateRandomNumber(1,999999,1)[0]);
        }
        if(null!=pay_type&&pay_type.length()>0){
            smf.setPay_type(pay_type);
        }else{
            smf.setPay_type("PAY_SCAN");
        }
        if(null!=pay_channel&&pay_channel.length()>0){
            smf.setPay_channel(pay_channel);
        }else{
            smf.setPay_channel("Wechat");
        }
        if(null!=auth_code&&auth_code.length()>0){
//            if("PAY_KEY".equals(pay_type)){
//                smf.setAuth_code(auth_code);
//            }else{
//                smf.setAuth_code("");
//            }
            smf.setAuth_code(auth_code);
        }else{
            smf.setAuth_code("123");
        }
        if(null!=notify_url&&notify_url.length()>0){
            smf.setNotify_url(notify_url);
        }else{
            smf.setNotify_url("");
        }
        smf.setOrder_no(IdWorker.getIdWorker().nextId()+"");
        smf.setSubject("测试订单");
        smf.setMemo("测试订单备注");
        out.print(toPay(smf));
        out.flush();
    }

}
